package open.tech.dawn.core.base;

import cn.hutool.core.util.ReflectUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

@Data
@Slf4j
public class BaseEntity {

    /**
     * 空值校验
     */
    public void valid() {
        Field[] fields = ReflectUtil.getFields(getClass());
        if (fields == null || fields.length == 0)
            return;
        for (Field field : fields) {
            EntityValid entityValid = field.getAnnotation(EntityValid.class);
            if (entityValid == null)
                continue;
            Class<? extends EntityValidMethod>[] value = entityValid.value();
            if (value == null || value.length == 0)
                continue;
            String name = field.getName();
            String methodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
            Method method = ReflectUtil.getMethod(getClass(), methodName, field.getType());
            Object invoke = null;
            if (method == null) {
                try {
                    field.setAccessible(true);
                    invoke = field.get(this);
                } catch (Exception e) {
                    log.error("校验对象异常", e);
                }
            } else {
                try {
                    invoke = method.invoke(this);
                } catch (Exception e) {
                    log.error("校验对象异常", e);
                }
            }
            for (Class<? extends EntityValidMethod> c : value) {
                EntityValidMethod entityValidMethod = ReflectUtil.newInstance(c);
                entityValidMethod.valid(invoke, field, entityValid);
            }
        }
    }

}
